package com.yycx.module.file.provider.green;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.AcsRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yycx.common.constants.SettingConstant;
import com.yycx.common.utils.ApiAssert;
import com.yycx.common.utils.JsonUtils;
import com.yycx.common.utils.RedisUtils;
import com.yycx.module.file.client.vo.GreenProperties;
import com.yycx.module.file.client.vo.ImageSyncCheckResult;
import com.yycx.module.file.client.vo.TextCheckResult;
import com.yycx.module.file.client.vo.TextVo;
import com.yycx.module.file.provider.enums.TextCheckModelEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.*;

@Component
@Slf4j
public class AliGreenUtils {
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取配置
     *
     * @return
     */
    public GreenProperties getAliGreenProperties() {
        String v = redisUtils.getConfig(SettingConstant.ALI_GREEN);
        ApiAssert.isNotEmpty("您还未配置阿里云OSS", v);
        GreenProperties greenProperties = JSONUtil.toBean(v, GreenProperties.class);
        return greenProperties;
    }

    /**
     * 获取IAcsClient
     *
     * @param greenProperties
     * @return
     */
    public IAcsClient getIAcsClient(GreenProperties greenProperties) {
        String regionId = greenProperties.getRegionId();
        String accessKeyId = greenProperties.getAccessKeyId();
        String accessKeySecret = greenProperties.getAccessKeySecret();
        String domain = EndPointNameUtil.getDomain(regionId);
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint(regionId, regionId, "Green", domain);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        IAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    /**
     * 阿里内容安全检测文本
     *
     * @param textList
     * @param checkModelEnum
     */
    public TextCheckResult checkText(List<TextVo> textList, TextCheckModelEnum checkModelEnum) {
        GreenProperties aliGreenProperties = getAliGreenProperties();
        IAcsClient client = getIAcsClient(aliGreenProperties);
        TextScanRequest textScanRequest = new TextScanRequest();
        textScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
        textScanRequest.setMethod(MethodType.POST); // 指定请求方法
        textScanRequest.setEncoding("UTF-8");
        textScanRequest.setRegionId(aliGreenProperties.getRegionId());

        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        for (TextVo textVo : textList) {
            Map<String, Object> task1 = new LinkedHashMap<String, Object>();
            task1.put("dataId", textVo.getDataId());
            task1.put("content", textVo.getContent());
            tasks.add(task1);
        }
        JSONObject data = new JSONObject();
        data.put("scenes", Arrays.asList(checkModelEnum.getCheckModel()));
        data.put("tasks", tasks);
        try {
            textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
            textScanRequest.setConnectTimeout(3000);
            textScanRequest.setReadTimeout(6000);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = doAction(client, textScanRequest);
        TextCheckResult textCheckResult = JsonUtils.jsonToBean(jsonObject.toJSONString(), TextCheckResult.class);
        return textCheckResult;
    }

    /**
     * 阿里内容安全检测图片(同步检测方法)
     *
     * @param dataId
     * @param imgUrl
     * @param scenes porn: 色情 terrorism: 暴恐  qrcode: 二维码  ad: 图片广告  ocr: 文字识别
     */
    public ImageSyncCheckResult imageSyncScan(String dataId, String imgUrl, String scenes) {
        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task = new LinkedHashMap<String, Object>();
        task.put("dataId", dataId);
        task.put("url", imgUrl);
        task.put("time", new Date());
        ImageSyncCheckResult imageSyncCheckResult = imagesSyncScan(tasks, scenes);
        return imageSyncCheckResult;
    }

    /**
     * 阿里内容安全检测图片(同步检测方法)
     *
     * @param tasks
     * @param scenes porn: 色情 terrorism: 暴恐  qrcode: 二维码  ad: 图片广告  ocr: 文字识别
     */
    public ImageSyncCheckResult imagesSyncScan(List<Map<String, Object>> tasks, String scenes) {
        GreenProperties aliGreenProperties = getAliGreenProperties();
        IAcsClient client = getIAcsClient(aliGreenProperties);
        ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
        imageSyncScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
        imageSyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法
        imageSyncScanRequest.setEncoding("utf-8");
        imageSyncScanRequest.setRegionId(aliGreenProperties.getRegionId());
        JSONObject data = new JSONObject();
        data.put("scenes", Arrays.asList(scenes.split(",")));
        data.put("tasks", tasks);
        try {
            imageSyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = doAction(client, imageSyncScanRequest);
        ImageSyncCheckResult imageSyncCheckResult = JsonUtils.jsonToBean(jsonObject.toJSONString(), ImageSyncCheckResult.class);
        return imageSyncCheckResult;
    }

    private JSONObject doAction(IAcsClient acsClient, AcsRequest request) {
        JSONObject response = new JSONObject();
        try {
            HttpResponse httpResponse = acsClient.doAction(request);
            response = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return response;
    }

}
